package com.lagou.curator;

import com.lagou.client.RpcConsumerManager;
import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.ZkClient;

import java.util.ArrayList;
import java.util.List;

/**
 * GetNoteCurator
 *
 * @author achilles
 */
public class GetNoteCurator {

    private static final String PATH = "/lg-curator";

    private ZkClient zkClient;

    public GetNoteCurator() {
        zkClient = new ZkClient("101.37.159.186:2181");
    }

    public void initData() {
        if (zkClient.exists(PATH)) {
            List<String> children = zkClient.getChildren(PATH);
            for (String child : children) {
                String childPath = PATH + "/" + child;
                Object obj = zkClient.readData(childPath);
                RpcConsumerManager.addRpcConsumer(String.valueOf(obj));
            }
        }
    }

    public void subscribeChildChanges() {
        if (zkClient.exists(PATH)) {
            zkClient.subscribeChildChanges(PATH, new IZkChildListener() {
                @Override
                public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception {
                    if (currentChilds != null && currentChilds.size() > 0) {
                        List<String> data = new ArrayList<>(currentChilds.size());
                        for (String child : currentChilds) {
                            String childPath = PATH + "/" + child;
                            Object obj = zkClient.readData(childPath);
                            data.add(String.valueOf(obj));
                        }
                        RpcConsumerManager.rpcConsumerMapChanged(data);
                    } else {
                        RpcConsumerManager.rpcConsumerMapChanged(null);
                    }
                }
            });
        }
    }

    public List<String> getAddressList(){
        List<String> addressList = new ArrayList<>();
        if (zkClient.exists(PATH)) {
            List<String> children = zkClient.getChildren(PATH);
            for (String child : children) {
                String childPath = PATH + "/" + child;
                Object obj = zkClient.readData(childPath);
                addressList.add(String.valueOf(obj));
            }
        }
        return addressList;
    }
}
